package dao;

import bean.User;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.lang.NonNull;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {
    private boolean completed;

    @Override
    public boolean save(User user) {
        try {
            String userName = user.getUserName();
            // 如果在数据表中没有找到用户名字段为指定值的记录
            if (!find(userName)) {
                getHibernateTemplate().save(user);
                completed = true;
            }
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        }
        return completed;
    }

    /**
     * 查找具有指定名称和密码的用户的id
     */
    @Override
    public int find(User user) {
        int userId = 0;
        try {
            DetachedCriteria detached = DetachedCriteria.forClass(User.class);
            // 查询userName、password字段的值为指定值的userId数量
            detached.setProjection(Projections.id())
                .add(Restrictions.eq("userName", user.getUserName()))
                .add(Restrictions.eq("password", user.getPassword()));
            List<?> list = getHibernateTemplate().findByCriteria(detached);
            // 从有序集合中取出唯一元素userId的值
            if (list.size() > 0 && (int) list.get(0) > 0) {
                userId = (int) list.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userId;
    }

    /**
     * 根据指定用户名称查找符合条件的行的数量
     */
    @Override
    public boolean find(String userName) {
        try {
            DetachedCriteria detached = DetachedCriteria.forClass(User.class);
            detached.setProjection(Projections.rowCount())
                .add(Restrictions.eq("userName", userName));
            List<?> list = getHibernateTemplate().findByCriteria(detached);
            if ((long) list.get(0) > 0) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean update(int userId, @NonNull String newPassword) {
        try {
            User user = getHibernateTemplate().get(User.class, userId);
            user.setPassword(newPassword);
            getHibernateTemplate().update(user);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        }
        return completed;
    }

    @Override
    public boolean delete(int userId) {
        try {
            User user = getHibernateTemplate().get(User.class, userId);
            getHibernateTemplate().delete(user);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        }
        return completed;
    }
}
